/**
 * axios封装
 * 请求拦截、响应拦截、错误统一处理
 */
import axios from "axios";
import router from "../../../router";
import store from "../../../store/index";
import ElementUI from "element-ui";
var md5 = require("md5");
import Cookies from "js-cookie";

/**
 * 跳转登录页
 * 携带当前页面路由，以期在登录页面完成登录后返回当前页面
 */
const toLogin = () => {
  if (
    router.currentRoute.fullPath.indexOf("/login") < 0 &&
    router.currentRoute.fullPath.indexOf("/plugin-index") < 0
  ) {
    router.replace({
      path: "/login",
      query: {
        redirect: router.currentRoute.fullPath,
      },
    });
  }
};

/**
 * 请求失败后的错误统一处理
 * @param {Number} status 请求失败的状态码
 */
const errorHandle = (code, status) => {
  // console.log(code, status);
  store.commit("setIsLoading", false);
  if (code == 602) {
    ElementUI.Message.error("签名效验失败");
    toLogin();
  }
  if (status == 602) {
    toLogin();
  }
};

// 创建axios实例
var instance = axios.create({ timeout: 1000 * 12 });
// 设置post请求头
instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";
/**
 * 请求拦截器
 * 每次请求前，如果存在token则在请求头中携带token
 */

instance.interceptors.request.use(
  (config) => {
    // 登录流程控制中，根据本地是否存在token判断用户的登录情况
    // 但是即使token存在，也有可能token是过期的，所以在每次的请求头中携带token
    // 后台根据携带的token判断用户的登录情况，并返回给我们对应的状态码
    // 而后我们可以在响应拦截器中，根据状态码进行一些统一的操作。

    // const token = store.state.token;
    // token && (config.headers.Authorization = token);
    // const uid = store.state.uid;
    const uid = Cookies.get("adminuid") || "";

    var configUrl = config.url.slice(config.url.lastIndexOf("/") + 1);
    // var arr1 = ["saveedit", "saveadd"];
    // if (arr1.indexOf(configUrl) >= 0) {
    store.commit("setIsLoading", true);
    // }
    if (uid == "") {
      toLogin();
    }
    config.headers.headuid = uid;
    const meid = "";
    config.headers.meid = meid;
    const extra = "";
    config.headers.extra = extra;

    const time = parseInt(new Date().getTime() / 1000) + "";
    config.headers.timestamp = time;

    const admin_key = localStorage.getItem("admin_key") || "";
    var str = config.data;
    // str = str.replace(/undefined/gi, "");
    var url = "";
    if (str == "") {
      url =
        "admin_key=" +
        admin_key +
        "&headuid=" +
        uid +
        "&timestamp=" +
        time +
        "&meid=" +
        "" +
        "&extra=" +
        "";
    } else {
      url =
        str +
        "&admin_key=" +
        admin_key +
        "&headuid=" +
        uid +
        "&timestamp=" +
        time +
        "&meid=" +
        "" +
        "&extra=" +
        "";
    }
    var arr = url.split("&");

    for (var i in arr) {
      if (arr[i].indexOf("%") >= 0) {
        arr[i] = decodeURIComponent(arr[i]);
      }
    }

    let obj = {};
    let arr2 = arr;
    arr2.forEach((item) => {
      item = item.split("=");
      var two = "";
      for (let index = 1; index < item.length; index++) {
        if (item.length > 2) {
          two = two + item[index] + "=";
        } else {
          two = two + item[index];
        }
      }
      if (item.length > 2) {
        two = two.substring(0, two.length - 1);
      }
      obj[item[0]] = two;
    });
    var obj_str = Object.keys(obj).sort();
    var str = "";

    obj_str.forEach((item) => {
      str = str + `${item}=${obj[item] || ""}&`;
    });
    str = str.substring(0, str.length - 1);
    // console.log(str);
    config.data += "&sign=" + md5("@" + str + "@");
    return config;
  },
  (error) => Promise.error(error)
);

// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  (res) =>
    res.status === 200
      ? (errorHandle(res.status, res.data.code), Promise.resolve(res))
      : (store.commit("setIsLoading", false), Promise.reject(res)),
  // 请求失败
  (error) => {
    const { response } = error;
    if (response) {
      // 请求已发出，但是不在2xx的范围
      errorHandle(response.status, response.data.code, response);
      return Promise.reject(response);
    } else {
      // 处理断网的情况
      // eg:请求超时或断网时，更新state的network状态
      // network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
      // 关于断网组件中的刷新重新获取数据，会在断网组件中说明
      // store.commit("changeNetwork", false);
    }
  }
);
export default instance;
